<template>
  <Card :bordered="false">
    <a-button @click="back">返回</a-button>

    <Collapse style="margin-top: 15px" v-model:activeKey="activeKey">
      <CollapsePanel v-for="panel in collapsePanelList" :key="panel.value" :header="panel.label">
        <!--        基础信息-->
        <BasicForm v-if="panel.value === 'basic'" @register="registerForm">
          <template #billImageList="{ model, field }">
            <ImagePreviewGroup>
              <Image
                style="width: 100px; height: 100px"
                v-for="item in model[field] || []"
                :src="item"
                :key="item"
              />
            </ImagePreviewGroup>
          </template>
        </BasicForm>
        <!--        产品信息-->
        <template v-if="panel.value === 'product'">
          <BasicTable @register="registerTable" />
          <a v-if="!ifCheck" @click="handleAddProduct">添加产品</a>
        </template>
        <!--        送货信息-->
        <BasicForm v-if="panel.value === 'deliver'" :disabled="ifCheck" @register="registerDForm">
          <template #addr="{ model, field }">
            <RegionCascader v-model="model[field]" @checked-details="handleCascaderData" />
          </template>
        </BasicForm>
      </CollapsePanel>
    </Collapse>

    <div v-if="!ifCheck" style="margin-top: 20px">
      <a-button style="margin-right: 15px" @click="back">返回</a-button>
      <a-button type="primary" @click="handleConfirm">确认</a-button>
    </div>

    <ProductModal @register="registerModal" @ok="handleAddProductOk" />
  </Card>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import ProductModal from './modal.vue';
  import mcApi from 'mc-c2b2m-operator-api';
  import { useModal } from '@/components/Modal';
  import { formatToDateTime } from '@/utils/dateUtil';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicTable, useTable } from '@/components/Table';
  import { back, useActionType } from '@/hooks/web/useCommon';
  import { RegionCascader } from '@/components/RegionCascader';
  import { LogisticsBillDetailModel } from 'mc-c2b2m-operator-api/types/production';
  import { Card, Image, Collapse, CollapsePanel, ImagePreviewGroup } from 'ant-design-vue';
  import {
    productColumns,
    basicFormSchema,
    collapsePanelList,
    deliverFormSchema,
  } from '@/views/production/logistics/data';

  const { ProductionModule } = mcApi;
  const { LogisticsApi } = ProductionModule;

  // 基础信息配置
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: basicFormSchema,
    showActionButtonGroup: false,
  });
  // 产品信息配置
  const [registerTable, { setTableData, getDataSource }] = useTable({
    striped: false,
    bordered: true,
    canResize: false,
    showIndexColumn: false,
    columns: productColumns,
  });
  // 送货信息配置
  const [
    registerDForm,
    { resetFields: resetDFields, setFieldsValue: setDFieldsValue, validate: validateD },
  ] = useForm({
    labelWidth: 150,
    schemas: deliverFormSchema,
    showActionButtonGroup: false,
  });
  // 产品选择配置
  const [registerModal, { openModal, closeModal }] = useModal();

  const activeKey = ref<string[]>(collapsePanelList.map((panel) => panel.value));
  const { ifCheck, setActionType } = useActionType();
  const query = useRoute().query;
  onMounted(async () => {
    setActionType();
    await resetFields();
    await resetDFields();
    if (ifCheck.value) {
      await updateSchema({ field: 'billImageList', slot: 'billImageList' });
      const id = query?.id + '';
      id &&
        LogisticsApi.getLogisticsBill(id).then((res: LogisticsBillDetailModel) => {
          if (!res.id) return;
          setFieldsValue(res);
          setTableData(res.billItemList || []);
          setDFieldsValue(res);
        });
    }
  });

  const { createMessage } = useMessage();
  const addrData = ref<any>({});
  function handleCascaderData(data: any) {
    addrData.value = data || {};
  }
  // 添加产品
  function handleAddProduct() {
    openModal(true, {
      dataSource: getDataSource(),
    });
  }
  // 添加产品完毕
  function handleAddProductOk(rows: any[]) {
    closeModal();
    setTableData(rows);
  }
  // 确认操作
  async function handleConfirm() {
    try {
      const values: any = await validate();
      const valuesD: any = await validateD();
      const data: any[] = getDataSource();
      if (!data?.length) {
        createMessage.error('请选择产品信息！');
        return;
      }
      const { deliveryTime } = valuesD;
      const model = {
        ...valuesD,
        ...addrData.value,
        billImageList: values.billImageList,
        deliveryTime: formatToDateTime(deliveryTime, 'YYYY-MM-DD HH:mm:ss.SSS'),
        billItemList: data.map((item: any) => {
          const { orderId, orderItemId } = item;
          return {
            salesOrderId: orderId,
            salesOrderItemId: orderItemId,
          };
        }),
      };
      delete model['addr'];
      await LogisticsApi.createLogisticsBill(model);
      createMessage.success('新增成功！');
      back();
    } catch (e) {
      e?.errorFields?.length && createMessage.warning('请完善数据！');
    }
  }
</script>

<style scoped lang="scss">
  :deep(.ant-input-disabled) {
    color: #000000e0;
  }
</style>
